package drds.plus.executor;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import drds.plus.api.Session;
import drds.plus.common.jdbc.Parameters;
import drds.plus.common.properties.ParametersManager;
import drds.plus.executor.repository.Repository;
import drds.plus.executor.table.ITable;
import drds.plus.executor.table.ITemporaryTable;
import drds.plus.executor.transaction.Transaction;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * 一次执行过程中的上下文
 */
@Slf4j
public class ExecuteContext {

    /**
     * 当前运行时的存储对象
     */
    @Setter
    @Getter
    private Repository repository;

    /**
     * 是否自动关闭结果集。目前这个东西已经基本无效。除了在update等查询中有使用
     */
    @Setter
    @Getter
    private boolean closeResultCursor;
    /**
     * 当前事务
     */
    @Setter
    @Getter
    private Transaction transaction;
    @Setter
    @Getter
    private Map<String, Object> extraCmds = new HashMap();
    @Setter
    @Getter
    private ParametersManager parametersManager = new ParametersManager(extraCmds);
    @Setter
    @Getter
    private Parameters parameters = null;
    @Setter
    @Getter
    private ExecutorService executorService;
    @Setter
    @Getter
    private boolean autoCommit = true;
    @Setter
    @Getter
    private String groupHint = null;
    @Setter
    @Getter
    private int autoGeneratedKeys = -1;
    @Setter
    @Getter
    private volatile Cache<String, ITemporaryTable> tableNameToTemporaryTableCache = CacheBuilder.newBuilder().build();
    @Setter
    @Getter
    private Session session = null;
    @Setter
    @Getter
    private String sqlMode = null;
    @Setter
    @Getter
    private String sql = null;
    @Setter
    @Getter
    private String applicationId;

    public ExecuteContext() {

    }


    public void setExtraCmds(Map<String, Object> extraCmds) {
        this.extraCmds = extraCmds;

        this.parametersManager = new ParametersManager(extraCmds);
    }


    public void cleanTempTables() {
        for (ITable table : getTableNameToTemporaryTableCache().asMap().values()) {
            try {
                table.close();
            } catch (Throwable e) {
                log.warn("temp where close failed", e);
            }
        }
    }

}
